package cn.iocoder.yudao.module.design.service.diary;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.design.controller.admin.diary.vo.*;
import cn.iocoder.yudao.module.design.convert.diary.DiaryConvert;
import cn.iocoder.yudao.module.design.dal.dataobject.diary.DiaryDO;
import cn.iocoder.yudao.module.design.dal.dataobject.pic.PicDO;
import cn.iocoder.yudao.module.design.dal.mysql.diary.DiaryMapper;
import cn.iocoder.yudao.module.design.enums.design.PicSourceTypeEnum;
import cn.iocoder.yudao.module.design.enums.design.PicUploadTypeEnum;
import cn.iocoder.yudao.module.design.service.pic.PicService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.design.enums.ErrorCodeConstants.DIARY_NOT_EXISTS;

/**
 * 日记 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DiaryServiceImpl implements DiaryService {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    @Resource
    private DiaryMapper diaryMapper;

    @Resource
    private PicService picService;


    @Override
    public Long createDiary(DiaryCreateReqVO createReqVO) {
        // 插入
        DiaryDO diary = DiaryConvert.INSTANCE.convert(createReqVO);
        diary.setDate(new Date());
        diary.setCreator(SecurityFrameworkUtils.getLoginUserId().toString());
        int insert = diaryMapper.insert(diary);
        if(insert > 0){
            PicDO picDo = new PicDO();
            picDo.setHouseId(createReqVO.getHouseId());
            picDo.setFlowId(createReqVO.getFlowId());
            picDo.setNodeId(createReqVO.getNodeId());
            picDo.setItemId(diary.getId());
            picDo.setSourceType(PicSourceTypeEnum.PIC_SOURCE_TYPE_ENUM_003.getCode());
            picDo.setUploadType(PicUploadTypeEnum.PIC_UPLOAD_TYPE_ENUM_0.getCode());
            // 保存图片文件
            picService.savePicData(picDo,createReqVO.getFileList());
        }else{
            throw new RuntimeException("创建失败");
        }
        // 返回
        return diary.getId();
    }
    @Override
    public void createDiarys(List<Map>lst) {
        // 转batch后插入
        List<DiaryDO>doList=new ArrayList<>();
        for (Map map:lst
             ) {
            DiaryDO diaryDO=new DiaryDO();
            diaryDO.setNodeId((Long) map.get("nodeId"));
            diaryDO.setDate(new Date());
            diaryDO.setHouseId((Long) map.get("houseId"));
            doList.add(diaryDO);
        }
        diaryMapper.insertBatch(doList);
        // 返回
        return ;
    }

    @Override
    public void updateDiary(DiaryUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateDiaryExists(updateReqVO.getId());
        // 更新
        DiaryDO updateObj = DiaryConvert.INSTANCE.convert(updateReqVO);
        int updateById = diaryMapper.updateById(updateObj);
        if(updateById > 0){
            PicDO picDo = new PicDO();
            picDo.setHouseId(updateReqVO.getHouseId());
            picDo.setFlowId(updateReqVO.getFlowId());
            picDo.setNodeId(updateReqVO.getNodeId());
            picDo.setItemId(updateReqVO.getId());
            picDo.setSourceType(PicSourceTypeEnum.PIC_SOURCE_TYPE_ENUM_003.getCode());
            picDo.setUploadType(PicUploadTypeEnum.PIC_UPLOAD_TYPE_ENUM_0.getCode());
            // 保存图片文件
            picService.savePicData(picDo,updateReqVO.getFileList());
        }else{
            throw new RuntimeException("修改失败");
        }

    }

    @Override
    public void deleteDiary(Long id) {
        // 校验存在
        this.validateDiaryExists(id);
        // 删除
        diaryMapper.deleteById(id);
    }

    private void validateDiaryExists(Long id) {
        if (diaryMapper.selectById(id) == null) {
            throw exception(DIARY_NOT_EXISTS);
        }
    }

    @Override
    public DiaryDO getDiary(Long id) {
        return diaryMapper.selectById(id);
    }

    @Override
    public List<DiaryDO> getDiaryList(Collection<Long> ids) {
        return diaryMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<DiaryDO> getDiaryPage(DiaryPageReqVO pageReqVO) {


        return diaryMapper.selectPage(pageReqVO);
    }

    @Override
    public    List<DiaryRespGroupVO>  getDiaryPageResp(DiaryPageReqVO pageReqVO) {
        // 只查询本人的
        pageReqVO.setCreator(SecurityFrameworkUtils.getLoginUserId().toString());
        PageResult<DiaryDO> pageResult =  diaryMapper.selectPage(pageReqVO);

        PicDO  picDo= new PicDO();
        List<DiaryDO> list = pageResult.getList();
        List<DiaryRespVO> diaryRespVOS = new ArrayList<>();

        for ( DiaryDO respVo: list  ) {
            DiaryRespVO  diaryRespVO  =  DiaryConvert.INSTANCE.convert(respVo);
            picDo= new PicDO();
            picDo.setHouseId(respVo.getHouseId());
            picDo.setFlowId(respVo.getFlowId());
            picDo.setNodeId(respVo.getNodeId());
            picDo.setItemId(respVo.getId());

            picDo.setSourceType(PicSourceTypeEnum.PIC_SOURCE_TYPE_ENUM_003.getCode());
            picDo.setUploadType(PicUploadTypeEnum.PIC_UPLOAD_TYPE_ENUM_0.getCode());
            diaryRespVO.setFileList(picService.getPicData(picDo));
            diaryRespVOS.add(diaryRespVO);
        }
        // 使用Stream API对日期进行分组倒序排列，并转换格式

        Map<Date, List<DiaryRespVO>> grouped = diaryRespVOS.stream()
                .collect(Collectors.groupingBy(DiaryRespVO::getDate)); // 按照日期进行分组

        List<DiaryRespGroupVO> result = grouped.entrySet().stream()
                .map(entry -> {
                    DiaryRespGroupVO group = new DiaryRespGroupVO();
                    group.setDate(entry.getKey());
                    group.setData(entry.getValue());
                    return group;
                })
                .collect(Collectors.toList());
        return result;
    }


    @Override
    public List<DiaryDO> getDiaryList(DiaryExportReqVO exportReqVO) {
        return diaryMapper.selectList(exportReqVO);
    }

}
